<template>
    <div class="userOut">
        <!-- 面包屑 -->
        <el-card>
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: 'welcom' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>用户管理</el-breadcrumb-item>
                <el-breadcrumb-item>用户列表</el-breadcrumb-item>
            </el-breadcrumb>
        </el-card>


        <!--，内容区域 -->
        <el-card>
            <!-- 搜索和添加区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" class="input-with-select" v-model="selectUser.key" clearable
                        @clear="getData()">
                        <el-button slot="append" icon="el-icon-search" @click="getData()"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>

            </el-row>
            <!-- 数据区域 -->
            <el-table :data="userList" style="width: 100%" :border="true" :stripe="true">
                <el-table-column type="index" label="序号" align='center'></el-table-column>
                <el-table-column prop="userName" label="账号" align='center'></el-table-column>
                <el-table-column prop="nickName" label="昵称" align='center'></el-table-column>
                <el-table-column label="头像" align='center'>
                    <template slot-scope="scope">
                        <img :src="scope.row.imgUrl" style="width: 100px; height: 100px;" />
                    </template>
                </el-table-column>
                <el-table-column prop="phone" label="电话" align='center'></el-table-column>
                <el-table-column prop="gender" label="性别" align='center'>
                    <template slot-scope="scope">
                        <div v-if="scope.row.gender === 0">未设置</div>
                        <div v-else>{{ scope.row.gender === 1 ? '男' : '女' }}</div>

                    </template>
                </el-table-column>
                <el-table-column label="状态" align='center'>
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.state" active-color="#13ce66" inactive-color="#f1f1f1"
                            :active-value="0" :inactive-value="1" @change="userStateChanged(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="addTime" label="注册时间" align='center' :formatter="dateFormat"></el-table-column>
                <el-table-column label="操作" align='center'>
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini"
                            @click="showEditDialog(scope.row)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                            @click="delUser(scope.row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="selectUser.currentPage" :page-sizes="[1, 2, 5, 10]" :page-size="selectUser.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>

        <!-- 添加弹窗 -->
        <el-dialog @close="addDialogClosed" title="添加用户" :visible.sync="addDialogVisible" width="50%">
            <!-- 内容 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="addForm.userName"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="userPwd">
                    <el-input v-model="addForm.userPwd"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="addForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickName">
                    <el-input v-model="addForm.nickName"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑弹窗 -->
        <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <!-- 内容 -->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="editForm.userName"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="editForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickName">
                    <el-input v-model="editForm.nickName"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="editForm.gender">
                        <el-radio label="1">男</el-radio>
                        <el-radio label="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>



<script>
import { selectUser, regUser, delUserById, updateUserAdmin } from '../../api/user/user.js'
export default {
    data() {
        //自定义验证规则
        //验证密码的规则
        var checkPwd = (rule, value, cb) => {
            const regPwd = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,18}$/
            if (regPwd.test(value)) {
                return cb()
            }
            return cb('密码必须包含数字和字母，且在6-18之间')
        }
        //验证手机号的规则
        var checkPhone = (rule, value, cb) => {
            const regPwd = /^1[3456789]\d{9}$/
            if (regPwd.test(Number(value))) {
                return cb()
            }
            return cb('请输入11位手机号')
        }

        return {
            //总数据
            userList: [],
            //传递参数
            selectUser: {
                key: null,
                //第几页
                currentPage: 1,
                //一页显示几条数据，默认5条
                pageSize: 5,
            },
            //总页数
            total: 0,
            //用户编辑弹窗状态
            editDialogVisible: false,
            //用户添加弹窗状态
            addDialogVisible: false,
            //添加用户的表单数据
            addForm: {
                userName: '',
                userPwd: '',
                phone: '',
                nickName: ''
            },
            //添加用户的表单数据的验证规则
            addFormRules: {
                userName: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                userPwd: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { validator: checkPwd, trigger: 'blur' }
                ],
                nickName: [
                    { required: true, message: '请输入昵称', trigger: 'blur' },
                    { min: 3, max: 10, message: '昵称长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { validator: checkPhone, trigger: 'blur' }

                ]
            },
            //编辑弹窗的数据表单
            editForm: {},
            //编辑弹窗的数据表单的验证规则
            editFormRules: {
                userName: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
                ],

                nickName: [
                    { required: true, message: '请输入昵称', trigger: 'blur' },
                    { min: 3, max: 10, message: '昵称长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { validator: checkPhone, trigger: 'blur' }
                ],
                gender: [
                    { required: true, message: '请选择性别', trigger: 'change' }
                ]
            }

        }
    },
    methods: {
        editDialogClosed() {
            //关闭校验以及重置
            this.$refs.editFormRef.resetFields()
        },
        //点击确认编辑用户
        editUser() {
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) return
                this.editForm.gender = Number(this.editForm.gender)
                await updateUserAdmin(this.editForm).then(res => {
                    if (res.data.status == 0) {
                        this.editDialogVisible = false
                        this.getData()
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        })
                    } else {
                        this.editForm.gender = String(this.editForm.gender)
                        this.$message.error(res.data.message)
                    }
                }).catch(err => { })

            })
        },
        //点击编辑用户,弹窗显示
        showEditDialog(row) {
            // console.log(row)
            // this.editForm={id,userName,phone,nickName,gender}=row
            this.editForm = {
                id: row.id,
                userName: row.userName,
                phone: row.phone,
                nickName: row.nickName,
                gender: row.gender === 0 ? null : row.gender + ''
            }
            this.editDialogVisible = true
        },
        //删除
        async delUser(row) {
            this.$confirm('确认删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                await delUserById(row.id).then(res => {
                    if (res.data.status === 0) {
                        this.userList = this.userList.filter(item => item.id != row.id)
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                    }
                })
            }).catch(() => { })
        },
        //弹窗点击确定添加用户
        addUser() {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return
                await regUser(this.addForm).then(res => {
                    if (res.data.status === 0) {
                        //隐藏弹窗
                        this.addDialogVisible = false
                        //刷新数据
                        this.getData()
                        this.$message({
                            message: '注册成功',
                            type: 'success'
                        })
                    } else {
                        this.$message.error(res.data.message)
                    }
                }).catch(err => {
                    console.log(err)
                })
            })
        },
        //弹窗关闭时触发
        addDialogClosed() {
            //关闭校验以及重置
            this.$refs.addFormRef.resetFields()
        },
        // 编写日期格式化方法
        dateFormat: function (row) {
            const date = row.addTime
            if (!date) {
                return ''
            }
            // 这里的格式根据需求修改
            return this.$moment(date).format('YYYY-MM-DD HH:mm:ss')
        },
        //状态值发生改变时触发
        userStateChanged(userInfo) {
            updateUserAdmin({ state: userInfo.state, id: userInfo.id }).then(res => {
                if (res.data.status === 0) {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                }
            })
        },
        //获取数据
        getData() {
            selectUser(this.selectUser).then(res => {
                if (res.data.status === 0) {
                    this.userList = res.data.data
                    this.total = res.data.totalpage
                }
            })
        },
        //改变一页显示多少数据
        handleSizeChange(newSize) {
            this.selectUser.pageSize = newSize
            this.getData()
        },
        //改变第几页
        handleCurrentChange(newPage) {
            this.selectUser.currentPage = newPage
            this.getData()
        }
    },
    created() {
        this.getData()
    }
}
</script>

<style scoped lang="less">
.userOut {}
</style>